package com.haidechizi.fastadmin.common.utils;

import com.haidechizi.fastadmin.modules.sys.service.SysConfigService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * 工具类，获取工程路径，用于设置代码的生成路径
 */
@Component
public class GlobalUtils implements ApplicationListener<ContextRefreshedEvent> {

    // 生成代码路径
    private static String projectPath = null;

    // 文件上传路径
    private static String filePath = null;

    private static SysConfigService sysConfigService;

    /**
     * 获取文件的存储类型
     * 1 本地
     * 2 云存储
     *
     * @return
     */
    public static String fileStorageType() {
        return Optional.ofNullable(sysConfigService.getValue("fileStorageType")).orElse("1");
    }

    public static String getFilePath() {
        return filePath;
    }


    /**
     * 获取工程路径
     *
     * @return
     */
    public static String getProjectPath() {
        // 如果配置了工程路径，则直接返回，否则自动获取。
        if (StringUtils.isNotBlank(projectPath)) {
            return projectPath;
        }
        try {
            File file = new DefaultResourceLoader().getResource("").getFile();
            if (file != null) {
                while (true) {
                    File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
                    if (f == null || f.exists()) {
                        break;
                    }
                    if (file.getParentFile() != null) {
                        file = file.getParentFile();
                    } else {
                        break;
                    }
                }
                projectPath = file.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return projectPath;
    }

    /**
     * 获取spring配置的变量
     *
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        projectPath = contextRefreshedEvent.getApplicationContext().getEnvironment().getProperty("projectPath");
        filePath = contextRefreshedEvent.getApplicationContext().getEnvironment().getProperty("fastAdmin.filePath");
        sysConfigService = contextRefreshedEvent.getApplicationContext().getBean(SysConfigService.class);
    }
}
